import { createStore } from 'vuex' 

const store = createStore({
  state: {
    // 初始化 state，从本地存储读取
    token: uni.getStorageSync('token') || '',
    userInfo: uni.getStorageSync('userInfo') || {},
    isLoggedIn: uni.getStorageSync('isLoggedIn') || false,
  },
  mutations: {
    // 设置 Token
    SET_TOKEN(state, token) {
      state.token = token;
      // 同步到本地存储
      if (token) {
        uni.setStorageSync('token', token);
        // 如果有 token，认为是登录状态
        state.isLoggedIn = true;
        uni.setStorageSync('isLoggedIn', true);
      } else {
        // 如果 token 为空，清除登录状态
        state.isLoggedIn = false;
        uni.setStorageSync('isLoggedIn', false);
      }
    },
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo || {}; 
      // 同步到本地存储
      uni.setStorageSync('userInfo', userInfo || {});
    },
    // 设置登录状态（可选，通常由 SET_TOKEN 触发）
    SET_LOGIN_STATUS(state, status) {
      state.isLoggedIn = !!status;
      uni.setStorageSync('isLoggedIn', !!status);
    },
    // 登出，清空所有状态和本地存储
    LOGOUT(state) {
      state.token = '';
      state.userInfo = {};
      state.isLoggedIn = false;

      // 清除本地存储
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
      uni.setStorageSync('isLoggedIn', false);
    }
  },
  actions: {
    // 登录 Action：接收 token 和 userInfo，提交到 mutations
    login({ commit }, { token, userInfo }) {
      commit('SET_TOKEN', token);
      commit('SET_USER_INFO', userInfo);
    },
    logout({ commit }) {
      commit('LOGOUT');
    },
    updateUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo);
    }
  },
  getters: {
    userAvatar: (state) => {
      return state.userInfo.avatar || '/static/avatar.webp';
    },
    userNickname: (state) => {
      return state.userInfo.nickname || '未设置昵称';
    }
  }
});

export default store;